/*
	Copyright (C) 2008 by Jean-François Geyelin
	jfgeyelin@gmail.com

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the
	Free Software Foundation, Inc.,
	51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

#include "AllSounds.h"


#include "settings.h"
#include "safeFileIO.h"
#include "StreamHandler.h"
#include "Sound.h"

AllSounds *AllSounds::instance = NULL;

AllSounds *AllSounds::getInstance(void) {
    if (instance==NULL) {
        instance = new AllSounds();
    }
    return instance;
}

void AllSounds::deleteInstance(void) {
    if (instance==NULL) {
        return;
    }
    delete instance;
    instance = NULL;
}



AllSounds::AllSounds(void) {
#ifndef NO_SOUND_EFFECT
    soundMap = new std::map<std::string,Sound*>;
    FILE *f = fopen_safe("sound/sound_key.txt","r");
    if (!f)
    LOG_ERROR("failed to load sound key map\n")
    std::string fileName,key;
    long volume;
	while (StreamHandler::readString(f,&fileName) && StreamHandler::readString(f,&key) && StreamHandler::readLong(f,&volume)) {
        addSound(fileName,key,(int)volume);
	}
    fclose(f);
    Settings s;
    loadSettings(&s);
    setMaxVolume((s.soundEffectsVolume*255)/100);
#endif
}

AllSounds::~AllSounds(void) {
#ifndef NO_SOUND_EFFECT
	std::map<std::string,Sound*>::iterator i = soundMap->begin();
	while(i != soundMap->end()) {
		delete i->second;
		i++;
	}
	delete soundMap;
#endif
}

void AllSounds::play(std::string key) {
#ifndef NO_SOUND_EFFECT

	//if (!settings.playSoundEffects)
	//return;
	Sound* sound = (*soundMap)[key];

	if (sound!=NULL) {
		sound->play();
	}

#endif
}


void AllSounds::play(std::string key, float percentage) {
#ifndef NO_SOUND_EFFECT

	//if (!settings.playSoundEffects)
	//return;
	Sound* sound = (*soundMap)[key];

	if (sound!=NULL) {
		sound->play(percentage);
	}

#endif
}

void AllSounds::addSound(std::string fileName, std::string key) {
#ifndef NO_SOUND_EFFECT
	(*soundMap)[key]=new Sound(fileName);
#endif
}

void AllSounds::addSound(std::string fileName, std::string key, int volume) {
    #ifndef NO_SOUND_EFFECT
    (*soundMap)[key]=new Sound(fileName, volume);
    #endif
}

void AllSounds::setMaxVolume(int volume) {
    #ifndef NO_SOUND_EFFECT
	std::map<std::string,Sound*>::iterator i = soundMap->begin();
	while(i != soundMap->end()) {
		i->second->setMaxVolume(volume);
		i++;
	}
	#endif
}


